package handlers

import (
	"github.com/gin-gonic/gin"
	"logi-flow/cache"
	"logi-flow/model"
	"logi-flow/pkg"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "不能为空",
		})
		return
	}
	var user model.User
	model.DB.Where("username=?", username).Find(&user)
	redis_key := "login_" + username
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if cacheData >= 3 {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "封禁",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Str(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if cacheData == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 400,
				"msg":  "错误3次,封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登陆成功",
	})
}
func UserRoleAdd(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	if uid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不能为空",
		})
		return
	}
	role := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	err := model.DB.Create(&role).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func RoleNodeAdd(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	if nid == 0 || rid == 0 {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "不能为空",
		})
		return
	}
	role := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	err := model.DB.Create(&role).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 400,
			"msg":  "添加失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
}
func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var role []model.Role
	model.DB.Table("roles").
		Joins("LEFT JOIN user_roles ON roles.id=user_roles.uid").
		Where("user_roles.uid=?", uid).
		Find(&role)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": role,
	})
}
func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var node []model.Node
	model.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON nodes.id=role_nodes.nid").
		Where("role_nodes.rid=?", rid).
		Find(&node)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": node,
	})
}
